package service

import (
	"errors"
	"ollama-go/dto"
	"ollama-go/entity"
	"ollama-go/query"
	"ollama-go/vo"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/sgorm"
	"github.com/androidsr/sc-go/sno"
)

var fwConfigService *FwConfigService

type FwConfigService struct {
}

func NewFwConfigService() *FwConfigService {
	if fwConfigService == nil {
		fwConfigService = new(FwConfigService)
	}
	return fwConfigService
}

// 使用id获取数据
func (m FwConfigService) Get(id string) *vo.FwConfigVO {
	data := new(entity.FwConfig)
	data.Id = id
	err := sgorm.DB.GetOne(data)
	if err != nil {
		return nil
	}
	return sc.Copy[vo.FwConfigVO](data)
}

// 保存数据
func (m FwConfigService) Save(dto *dto.FwConfigDTO) error {
	data := sc.Copy[entity.FwConfig](dto)
	data.Id = sno.GetString()
	err := sgorm.DB.Insert(data)
	return err
}

// 更新数据
func (m FwConfigService) UpdateById(dto *dto.FwConfigDTO) error {
	dbEntity := new(entity.FwConfig)
	dbEntity.Id = dto.Id
	sgorm.DB.GetOne(dbEntity)
	if dbEntity.TenantId != "" && dbEntity.TenantId != dto.TenantId {
		return errors.New("非本人创建不能修改")
	}
	sc.CopyTo(dto, dbEntity)
	err := sgorm.DB.UpdateById(dbEntity).Error
	return err
}

// 删除数据
func (m FwConfigService) DeleteById(id string) error {
	err := sgorm.DB.DeleteById(entity.FwConfig{}, id)
	return err
}

// 分页列表查询
func (m FwConfigService) QueryPage(query *query.FwConfigQueryDTO) *model.PageResult {
	sql := `select a.* from fw_config a where 1=1 `
	data := make([]vo.FwConfigVO, 0)
	b := sbuilder.StructToBuilder(query, sql)
	b.Or().Eq("a.is_open", "1")
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, query.BaseQueryDTO.Page, sql, values...)
}

// 分页下拉查询
func (m FwConfigService) QueryList(query *model.SelectQueryDTO) *model.PageResult {
	sql := `select a.id as value, a.name as label from fw_config a where 1=1 `
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(a.id,a.name)", query.Label)
	for k, v := range query.Vars {
		b.Eq(k, v)
	}
	b.Multiple().Ors(b.In("a.id", query.Selected))
	b.Or().Eq("a.is_open", "1")
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, &query.Page, sql, values...)
}
